# coding: gbk
'''
Created on 2010-12-17

@author: Administrator
'''
import wx
import win32con
import os
import ConfigParser
import pickle
from FileDialog import FileDialog

class TaskBarIcon(wx.TaskBarIcon):  
  ID_NoteBookTaskBar = wx.NewId()  
  ID_MenuQuit = wx.NewId()
  def __init__(self, frame):
    wx.TaskBarIcon.__init__(self)
    self.frame = frame
    self.SetIcon(wx.Icon(name='Notebook.ico', type=wx.BITMAP_TYPE_ICO), 'TaskBarIcon!')  
    self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarLeftDClick)  
    self.Bind(wx.EVT_MENU, self.OnClose, id=self.ID_MenuQuit)  
  
  def OnTaskBarLeftDClick(self, event):
    if self.frame.Show():
      self.frame.Show(True)
    else:
      self.frame.Show(False)
    if self.frame.IsIconized(): 
      self.frame.Iconize(False)
      if not self.frame.IsShown():
        self.frame.Show(True)
        self.frame.Raise()
  
  def OnClose(self, event):  
    self.frame.Destroy()
    self.frame.Close()
  
    # override  
  def CreatePopupMenu(self):  
    menu = wx.Menu()  
    menu.Append(self.ID_MenuQuit, 'Quite')  
    return menu
      
      
      
class NotebookFrame(wx.Frame):
  def __init__(self, parent, id):
    wx.Frame.__init__(self, parent, id, "Hy Notebook", size=(600,380),style=wx.DEFAULT_FRAME_STYLE|wx.STAY_ON_TOP )
    # Frame Attribute
    self.Centre()
    self.root = os.path.dirname(__file__)
    self.cacheDir = self.root + "\\Cache"
    self.confpath = self.root + "\\conf.ini"
    self.conf = self.LoadConfile()
    
    
    # Set Icon Of Application
    favicon = wx.Icon('Notebook.ico', wx.BITMAP_TYPE_ICO, 16, 16)
    self.SetIcon(favicon)
    # Set Task Icon
    self.taskBarIcon = TaskBarIcon(self)
    # Set Position Right Down
    mm=wx.DisplaySize()
    w = self.GetSize()[0]
    h = self.GetSize()[1]
    self.SetPosition((mm[0]-w, mm[1]-(h+30)))
    # Hotkey
    self.RegHotkey()
    self.Bind(wx.EVT_HOTKEY, self.OnHideWindows, id=self.hotkeyId)
    # Create Menu
    self.SetMenuBar(self.createMenuBar())
    
    # Add Notebook 
    self.nb = wx.Notebook(self, -1, style=wx.NB_TOP)
    self.InitNotebookPages(self.nb)
    
  
    
  def createMenuBar(self):
    """ Add Menu Bar"""
    menuBar = wx.MenuBar()
    menuFile = wx.Menu()
    menuEdit = wx.Menu()
    menuPage = wx.Menu()
    menuInsert = wx.Menu()
    menuTool = wx.Menu()
    menuHelp = wx.Menu()
    
    # File Menu
    openMenuItem = menuFile.Append(-1, "&Open", "Open a local file")
    saveMenuItem = menuFile.Append(-1, "&Save", "Save as Text File")
    hideMenuItem = menuFile.Append(-1, "&Hide", "Hide the main window")
    menuFile.AppendSeparator()
    quitMenuItem = menuFile.Append(-1, "&Quit", "Quit The Note Book")
    self.Bind(wx.EVT_MENU, self.OnClose, quitMenuItem)
    self.Bind(wx.EVT_MENU, self.OnHideWindows, hideMenuItem)
    self.Bind(wx.EVT_MENU, self.OnOpenFile, openMenuItem)
    
    # Edit Menu
    undoMenuItem = menuEdit.Append(-1, "&Undo", "Undo the last action")
    menuEdit.AppendSeparator()
    cutMenuItem = menuEdit.Append(-1, "&Cut", 
                                  "Cut The Selection Text To Clipboard")
    copyMenuItem = menuEdit.Append(-1, "C&opy", "Copy The Text to Clipboard")
    pasteMenuItem = menuEdit.Append(-1, "&Paste", "Paste Text from Clipboard")
    menuEdit.AppendSeparator()
    findMenuItem = menuEdit.Append(-1, "&Find", "Find The Text In Current Doc")
    nextMenuItem = menuEdit.Append(-1, "&Next", "Find Next Text you Searched")
    replaceMenuItem = menuEdit.Append(-1, "&Replace", "Replace Something")
    menuEdit.AppendSeparator()
    selectAllMenuItem = menuEdit.Append(-1, "&Select All", "Select All Text")
    
    # Page Menu
    addPageMenuItem = menuPage.Append(-1, "&New Page", "Add a new page")
    delPageMenuItem = menuPage.Append(-1, "&Delete Page", "Delete a new page")
    menuPage.AppendSeparator()
    modifyTitleMenuItem = menuPage.Append(-1, "&Modify Page Title", 
                                          "Modify The Title of Current Page")
    self.Bind(wx.EVT_MENU, self.OnAddNewPage, addPageMenuItem)
    self.Bind(wx.EVT_MENU, self.OnDeleteCurrentPage, delPageMenuItem)
    self.Bind(wx.EVT_MENU, self.OnModifyTitle, modifyTitleMenuItem)
    
    
    
    
    # Insert Menu
    insertSeparatorMenuItem = menuInsert.Append(-1, "Insert &Separator",
                                                "Insert A Separator")
    insertDateMenuItem = menuInsert.Append(-1, "Insert &Date Time", 
                                           "Insert Current Date Time")
    inertDateSeparatorMenuItem = menuInsert.Append(-1,
                                            "Insert Date &Time Separator", 
                                            "Insert Date Time Separator")
    
    # Tool Menu
    setWindowTopMenuItem = menuTool.Append(-1, "&Set Window Top", 
                                           "Setting Window On Top")
    menuTool.AppendSeparator()
    preferencesMenuItem = menuTool.Append(-1, "&Preferences", "Preferences")
    
    # Help Menu
    helpMenuItem = menuHelp.Append(-1, "&Help", "Help Doc")
    aboutMenuItem = menuHelp.Append(-1, "&About", "About Dialog")
    
    # Append Menu To MenuBar
    menuBar.Append(menuFile, "&File")
    menuBar.Append(menuEdit, "&Edit")
    menuBar.Append(menuPage, "&Page")
    menuBar.Append(menuInsert, "&Insert")
    menuBar.Append(menuTool, "&Tool")
    menuBar.Append(menuHelp, "&Help")
    
    # Menu Global Action
    self.Bind(wx.EVT_CLOSE, self.OnWindowClose)
    self.Bind(wx.EVT_ICONIZE, self.OnMinWindow)
    
    return menuBar
  
  
  # Event Method
  def OnClose(self, event):
    self.Close()
    
  def OnWindowClose(self, event):
    self.taskBarIcon.Destroy()
    self.Destroy()
    
  def OnAddNewPage(self, event):
    self.AddNewPage()
    
  def OnDeleteCurrentPage(self, event):
    if self.nb.GetPageCount() > 1:
      n = self.nb.GetSelection()
      self.nb.DeletePage(n)
      # Delete Text Cache File
      pass
  
  def OnHideWindows(self, event):
    if self.Show():
      self.Show(True)
    else:
      self.Show(False)
  
  def OnMinWindow(self, event):
    self.Show(False)
    
  def OnOpenFile(self, event):
    dlg = wx.FileDialog(self, message="Open a file", defaultDir="D:\\", 
                  wildcard="*.*", style=wx.OPEN)
    if dlg.ShowModal() == wx.ID_OK:
      filepath = dlg.GetPath()
      self.AddNewPageWithText(filepath)
  
  def OnModifyTitle(self, event):
    dlg = wx.TextEntryDialog(None, "Please Enter The File New Name:", "Modify File Name")
    if dlg.ShowModal() == wx.ID_OK:
      newFileName = dlg.GetValue()
      page = self.nb.GetSelection()
      self.nb.SetPageText(page, newFileName)


  # Comment Method
  def InitNotebookPages(self, nb):
    itemsCache = self.conf.items("Cache")
    if len(itemsCache) == 0:
      richTextCtrlTmp = wx.TextCtrl(nb, -1,"", style=wx.TE_MULTILINE)
      nb.AddPage(richTextCtrlTmp,"Default")
      richTextCtrlTmp.SetFocus()
    else:
      # Load Cache File
      self.LoadCacheFiles(itemsCache)
    
  def RegHotkey(self):
    self.hotkeyId = 100
    self.RegisterHotKey(self.hotkeyId, win32con.MOD_ALT, ord('Z'))
    
  def LoadConfile(self):
    
    conf = ConfigParser.ConfigParser()
    if not os.path.exists(self.confpath ):
      # Write Conf file
      conf.add_section("Cache")
      conf.add_section("Title")
      conf.add_section("TextCtrlID")
      conf.write(open(self.confpath ,'w'))
    else:
      # Read Conf File
      if not conf.has_section("Cache"):
        conf.add_section("Cache")
      if not conf.has_section("Title"):
        conf.add_section("Title")
      if not conf.has_section("TextCtrlID"):
        conf.add_section("TextCtrlID")
      conf.write(open(self.confpath ,'w'))
      conf.read(self.confpath )
    return conf
  
  def AddNewPage(self, filepath="", title="New Page"):
    richTextCtrlTmp = wx.TextCtrl(self.nb, -1,"", style=wx.TE_MULTILINE)
    if filepath == "":
      self.nb.AddPage(richTextCtrlTmp, title)
      n = self.nb.GetPageCount()
      self.nb.SetSelection(n - 1)
      richTextCtrlTmp.SetFocus()
    else:
      fileObject = open(filepath)
      richTextCtrlTmp.SetValue(fileObject.read())
      self.nb.AddPage(richTextCtrlTmp, self.conf.get("Title", title))
      if self.conf.has_section("TextCtrlID"):
        self.conf.set("TextCtrlID", title, richTextCtrlTmp.GetId())
      else:
        self.conf.add_section("TextCtrlID")
        self.conf.set("TextCtrlID", title, richTextCtrlTmp.GetId())
      self.conf.write(open(self.confpath, 'w'))
      
  def AddNewPageWithText(self, filepath):
    try:
      fileObject = open(filepath)
      richTextCtrlTmp = wx.TextCtrl(self.nb, -1, "", style=wx.TE_MULTILINE)
      self.nb.AddPage(richTextCtrlTmp, "New Page", True)
      richTextCtrlTmp.SetValue(fileObject.read())
    except :
      wx.MessageBox('Open File Failed', 'Info')

  def LoadCacheFiles(self, items):
    for eachLabel, eachCacheName in items:
      filepath = self.cacheDir + "\\" + eachCacheName
      if os.path.isfile(filepath):
        self.AddNewPage(filepath, eachLabel)
      


if __name__ == '__main__':
  app = wx.PySimpleApp()
  nf = NotebookFrame(None, -1)
  nf.Show()
  app.MainLoop()